import MySQLdb


def get_conn(host='', port=3306, db='', user='root', password=''):
    conn = MySQLdb.connect(
        host=host, 
        port=port, 
        db=db,
        user=user, 
        password=password,
        connect_timeout=3,
    )
    return conn


def check_config(host='', port=3306, user='root', password='', db='', table=''):
    try:
        port = int(port)
        conn = get_conn(host, port, db, user, password)
    except ValueError:
        return False, "端口号解析失败！", None
    except MySQLdb._exceptions.OperationalError as e:
        code, msg = e.args
        if code == 1045:
            return False, "数据库禁止访问！", None
        elif code == 1049:
            return False, "数据库不存在！", None
        elif code == 2002:
            return False, "无法访问本地数据库！", None
        elif code == 2003:
            return False, "无法访问数据库！", None
        else:
            return False, msg, None
    return True, "连接成功！", conn


def check_table_if_exists(conn, db, table):
    with conn.cursor() as cur:
        cur.execute('show databases;')
        databases = [i for row in cur.fetchall() for i in row]
        if db not in databases:
            return False

        cur.execute(f'use {db};')
        cur.execute('show tables;')
        tables = [i for row in cur.fetchall() for i in row]

        return table in tables